<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        #log-container {
            position: absolute;
            top: 0;
            left: 0;
            width: calc(100% - 20px);
            height: calc(100% - 20px);
            overflow-y: scroll;
            background: #333;
            color: #aaa;
            padding: 10px;
        }
    </style>
</head>
<body>
<div id="log-container"></div>
<script>
  const PAUSE_TIME = 5000;
  const container = document.getElementById('log-container');

  // 锁定
  let isLocked = false;
  // 是否是正常滚动， 如果是正常滚动，就不要锁定了
  let isAutoScrolling = false;
  // 暂停时间
  let pauseTimer = null;

  container.addEventListener('scroll', function (e) {
    pauseTimer && clearTimeout(pauseTimer);
    const offsetHeight = Math.ceil(container.scrollTop + container.offsetHeight)
    if (offsetHeight === container.scrollHeight) {
      isLocked = false;
      isAutoScrolling = false
    } else {
      if (!isAutoScrolling) {
        isLocked = true;
        // 10秒钟不动的话，就继续自动滚动
        pauseTimer = setTimeout(() => isLocked = false, PAUSE_TIME);
      }
    }
  })

  // 本地服务
  const websocket = new WebSocket('ws://127.0.0.1:9200/log', '123456');

  // ECS服务：https需要对应使用wss协议
  // const websocket = new WebSocket('wss://hzchuxi.cn/websocket/logger', '123456');

  websocket.onmessage = function (event) {
    container.innerHTML += `${event.data}</br>`
    if (!isLocked) {
      // 滚动条滚动到最低部
      container.scrollTop = container.scrollHeight;
      isAutoScrolling = true;
    }
  };

  //连接发生错误的回调方法
  websocket.onerror = function (event) {
      console.log(event)
    setMessageInnerHTML("error");
  };

  //连接成功建立的回调方法
  websocket.onopen = function (event) {
    setMessageInnerHTML("open");
  }


  //连接关闭的回调方法
  websocket.onclose = function () {
    setMessageInnerHTML("close");
  }

  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    websocket.close();
  }

  //将消息显示在网页上
  function setMessageInnerHTML(innerHTML) {
    document.getElementById('log-container').innerHTML += innerHTML + '<br/>';
  }

  //关闭连接
  function closeWebSocket() {
    websocket.close();
  }
</script>
</body>
</html>